package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.common.BaiDuMapResponse;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiDuMapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiDuMapUtil;
import com.sky.utils.DistanceCalculator;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapping shoppingCartMapping;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private BaiDuMapUtil baiDuMapUtil;
    @Autowired
    private BaiDuMapProperties baiDuMapProperties;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) throws Exception {
        Long userId = BaseContext.getCurrentId();
        // 查询地址簿，获取收货人信息
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 下单之前，判断用户的地址距离商家的距离是否满足要求
        // 计算距离，判断是否满足要求
        // 1、获取用户的地址经纬度
        BaiDuMapResponse userAddress = JSON.parseObject(baiDuMapUtil.requestGetAK(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail()), BaiDuMapResponse.class); // 用户地址

        // 2、获取商家的地址经纬度
        BaiDuMapResponse sellerAddress = JSON.parseObject(baiDuMapUtil.requestGetAK(baiDuMapProperties.getAddress()), BaiDuMapResponse.class); // 商家地址
        // 3、计算两地距离
        double lat1 = userAddress.getResult().getLocation().getLat();
        double lng1 = userAddress.getResult().getLocation().getLng();
        double lat2 = sellerAddress.getResult().getLocation().getLat();
        double lng2 = sellerAddress.getResult().getLocation().getLng();
        double distance = DistanceCalculator.calculateDistance(lat1, lng1, lat2, lng2);
        // 4、判断距离是否满足要求
        if (distance > 5) {
            throw new OrderBusinessException(MessageConstant.OUT_OF_DISTANCE);
        }
        // 查询用户信息，获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }
        // 查询购物车
        List<ShoppingCart> carts = shoppingCartMapping.list(userId);
        if (carts == null || carts.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 构造订单数据，存入order表中
        // 1、构造订单数据，存入order表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 1.1、补充缺失属性值
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setUserName(user.getName()); // 下单人
        ordersMapper.insert(orders);
        log.info("订单提交成功，订单id：" + orders.getId());

        // 2、构造订单详情数据，存入order_detail表中
        List<OrderDetail> orderDetails = new ArrayList<>();
        // 2.1、遍历购物车，构造订单详情数据
        for (ShoppingCart cart : carts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id"); // id不拷贝
            orderDetail.setOrderId(orders.getId()); // 关联订单id
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertList(orderDetails);
        // 3、清空购物车
        shoppingCartMapping.clean(userId);

        // 4、返回构造VO对象返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.selectById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));
        //
        // return vo;

        //业务处理，修改订单状态、来单提醒，本来应该在notify下的回调接口中处理。但是，我们的商户ID和小程序ID无法匹配，所以进入不到那个接口当中。
        paySuccess(ordersPaymentDTO.getOrderNumber());

        // 模拟支付成功
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .estimatedDeliveryTime(LocalDateTime.now().plusHours(1))  // 预计送达时间等于支付时间加1个小时
                .build();

        ordersMapper.update(orders);

        // 通过websocket向客户端推送消息 type orderId content
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1); // 1表示来单提醒 2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + outTradeNo + "已支付");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1、获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        // 2、构造分页条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 3、查询订单
        Page<OrderVO> orderVOPage = ordersMapper.list(userId);
        // 4、查询每个订单的订单详情
        orderVOPage.forEach(order -> {
            List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(order.getId());
            order.setOrderDetailList(orderDetails);
        });
        // 5、构造分页结果对象
        return new PageResult(orderVOPage.getTotal(), orderVOPage.getResult());
    }

    @Override
    public OrderVO orderDetail(Long id) {
        // 根据订单id查询
        OrderVO orderVO = ordersMapper.getByOrderId(id);
        // 根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        // 设置订单详情
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        // 根据id修改订单状态
        ordersMapper.update(orders);
    }

    @Override
    @Transactional
    public void repetition(Long id) {
        // 1、根据id查询当前订单
        Orders orders = ordersMapper.getByOrderId(id);
        // 根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        // 2、构造新订单数据
        Orders newOrders = new Orders();
        BeanUtils.copyProperties(orders, newOrders, "id"); // id不拷贝
        // 2.1、重新设置订单状态
        newOrders.setNumber(System.currentTimeMillis() + "");
        newOrders.setStatus(Orders.PENDING_PAYMENT);
        newOrders.setPayStatus(Orders.UN_PAID);
        newOrders.setCheckoutTime(null);
        newOrders.setEstimatedDeliveryTime(null);
        newOrders.setOrderTime(LocalDateTime.now());

        // 3、插入新的订单
        ordersMapper.insert(newOrders);
        log.info("订单提交成功，订单id：" + newOrders.getId());

        // 4、构造新订单详情数据
        List<OrderDetail> newOrderDetails = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            OrderDetail newOrderDetail = new OrderDetail();
            BeanUtils.copyProperties(orderDetail, newOrderDetail, "id"); // id不拷贝
            newOrderDetail.setOrderId(newOrders.getId()); // 关联新订单id
            newOrderDetails.add(newOrderDetail);
        }

        // 5、插入新的订单详情
        orderDetailMapper.insertList(newOrderDetails);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 1、构造分页条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 2、根据条件查询订单
        try (Page<OrderVO> orderVOPage = ordersMapper.conditionSearch(ordersPageQueryDTO)) {
            // 3、查询每个订单的订单详情
            orderVOPage.forEach(order -> {
                List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(order.getId());
                order.setOrderDetailList(orderDetails);
            });
            // 4、构造分页结果对象
            return new PageResult(orderVOPage.getTotal(), orderVOPage.getResult());
        }
    }

    @Override
    public OrderStatisticsVO statistics() {
        return ordersMapper.statistics();
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(ordersConfirmDTO.getStatus())
                .build();
        // 根据id修改订单状态
        ordersMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id修改订单状态
        ordersMapper.update(Orders.builder()
                .id(ordersRejectionDTO.getId())
                .cancelTime(LocalDateTime.now())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .build());
    }

    @Override
    public void admin_cancel(OrdersCancelDTO ordersCancelDTO) {
        ordersMapper.update(Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .build());
    }

    @Override
    public void delivery(Long id) {
        // 根据id修改订单状态
        ordersMapper.update(Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build());
    }

    @Override
    public void complete(Long id) {
        // 根据id修改订单状态
        ordersMapper.update(Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build());
    }

    @Override
    public void reminder(Long id) {
        // 1、根据id查询当前订单
        Orders orders = ordersMapper.getByOrderId(id);
        // 2、判断订单是否已经超时
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("type", 2); // 2表示催单提醒
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber() + "已催单");
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
